import { request } from "@umijs/max";
import requestTable from "@/utils/requestTable";
import type { TYPE } from "../types";
import storage from "../../utils/storage";
import { PidToChildren } from "../../utils";

/**
 * 获取系统资源数据，数据来源是用户登录时后台返回的"res"。
 */
async function resource(params: TYPE.ResItem) {
  let { path, method } = params;
  const { res } = storage.getData();
  const result = { success: true, data: res };

  if (!path && !method) return result;

  if (!path) path = "";
  const data: TYPE.ResItem[] = [];
  for (let i = 0; i < result.data.length; i += 1) {
    const item = result.data[i];
    let isOk = true;
    [
      // 按字符串大小写字母进行筛查
      [path, item.path.toUpperCase().indexOf(path.toUpperCase()) >= 0],
      [path, item.path.toLowerCase().indexOf(path.toLowerCase()) >= 0],
      [method, item.method === method],
    ].filter(([value]) => value).map(([_, condition]) => {
      if (!condition) isOk = false;
    });
    if (isOk) data.push(item);
  }
  result.data = data;
  return result;
}

/**
 * 接口测试，跳过"response"错误处理。
 */
function test(method: string, path: string, params: any) {
  const options: any = { method, skipErrorHandler: true };
  if (method === "post") options.data = params;
  else {
    const data: string[] = [];
    for (const key in params) {
      const value = params[key];
      data.push(key + "=" + value);
    }
    if (data.length) path += "?" + data.toString().replaceAll(",", "&");
  }
  return request(path, options);
}

/**
 * 获取系统访问日志数据
 */
function logger(params: any) {
  return requestTable("basic/logger", params);
}

/**
 * 封IP
 */
function forbidIP(ip: string, day: number) {
  return request("basic/logger/forbidIP", { params: { ip, day } });
}

/**
 * 封用户
 */
function forbidUser(userId: number, day: number) {
  return request("basic/logger/forbidUser", { params: { userId, day } });
}

/**
 * 获取单条用户数据
 */
function getUser(id: number) {
  return request("basic/logger/getUser", { params: { id } });
}

/**
 * 获取角色数据
 */
async function role() {
  const res = await request("basic/role", {});
  const data: TYPE.RoleItem[] = res.data.tableData;
  let menuData: TYPE.MenuItem[] = res.data.menuData;
  const resData: TYPE.ResItem[] = res.data.resData;

  // 建立映射，根据父菜单的id，获取父菜单的路径和索引。
  // 保存所有菜单id
  const mappingPath: any = {}, menuIds: number[] = [];
  menuData.map(({ id, pid, path }, index) => {
    if (!pid) mappingPath[id] = { path, index };
    menuIds.push(id);
  });

  // 遍历所有菜单，子菜单的路径左边加上父菜单的路径，并设置父菜单的children=[]。
  menuData = menuData.map(item => {
    const { pid } = item;
    if (!pid) return item;

    const { path, index } = mappingPath[pid];
    item.path = path + "/" + item.path;
    menuData[index].children = [];
    return item;
  });

  // 菜单挂载资源数据
  menuData = menuData.map(menu => {
    if (menu.children) return menu;

    resData.map(res => {
      if (res.path.indexOf(menu.path) === -1) return;

      if (!menu.children) menu.children = [];
      menu.children.push({ ...res, pid: menu.id });
    });
    return menu;
  });

  // 生成树形数据
  const treeData: TYPE.TreeItem[] = PidToChildren(menuData);
  return { data, treeData, menuIds: menuIds.toString() };
}
/**
 * 新增角色数据
 */
function roleAdd(data: TYPE.RoleItem) {
  return request("basic/role/add", { method: "post", data });
}
/**
 * 编辑角色数据
 */
function roleEdit(data: TYPE.RoleItem) {
  return request("basic/role/edit", { method: "post", data });
}
/**
 * 删除角色数据
 */
function roleRemove(id: number) {
  return request("basic/role/remove", { params: { ids: id } });
}

/**
 * 获取用户数据
 */
function user(params: any) {
  // 字符串转布尔值，例如："true" => true
  const statusMap: any = { true: true, false: false };
  const { status } = params;
  if (status) params.status = statusMap[status];
  return requestTable("basic/user", params);
}
/**
 * 新增用户数据
 */
function userAdd(data: TYPE.User) {
  return request("basic/user/add", { method: "post", data });
}
/**
 * 编辑用户数据
 */
function userEdit(data: TYPE.User) {
  return request("basic/user/edit", { method: "post", data });
}
/**
 * 删除用户数据
 */
function userRemove(id: number) {
  return request("basic/user/remove", { params: { ids: id } });
}
/**
 * 角色列表框数据
 */
function roleSelectData() {
  return request("basic/user/roleSelectData");
}

export default {
  resource, test,
  logger, forbidIP, forbidUser, getUser,
  role, roleAdd, roleEdit, roleRemove,
  user, userAdd, userEdit, userRemove, roleSelectData,
};
